#ifndef _graphy_polygon_h_
#define _graphy_polygon_h_
#include "graphic_public.h"
#include "wykobi/wykobi.hpp"


namespace polygon
{
	inline float_t cross_product(const point2d_t &x, const point2d_t &y)
	{
		return x[0]*y[1] - y[0]*x[1];
	}

	//get triangle's center of gravity
	inline void getTriangleCOG(point2d_t a, point2d_t b, point2d_t c, 
		point2d_t &center, float_t &weight){
			center = (a+b+c)/3.0;
			point2d_t ab, ac;
			ab = b - a;
			ac = c - a;
			weight = (float_t)(fabs(cross_product(ab, ac))/2.0);
	}

	inline void getLineCOG(point2d_t a, float_t weight_a, point2d_t b, float_t weight_b,
		point2d_t &center, float_t &weight) {
			point2d_t ab = b - a;
			center = a + ab * (1 - weight_a/(weight_a + weight_b));
			weight = weight_a + weight_b;
	}

	point2d_t GetPolygonCOG(const point2d_t *pt, int num, float_t &area_weight);

	inline bool line_intersect(const point2d_t &a, const point2d_t &b, const point2d_t &c, 
		const point2d_t &d, point2d_t &intersect_point) {
		return wykobi::intersect(a[0], a[1], b[0], b[1], c[0], c[1], d[0], d[1], intersect_point[0], intersect_point[1]);
	}

	bool intersect(const point2d_t *pts, int num, const point2d_t &a, const point2d_t &b, 
		int intersect_pos[2], float_t intersect_ratio[2]);

	bool CreateNewPolygonsFromIntersect(const point2d_t *pts, int num, int intersect_pos[2], 
		float_t intersect_ratio[2], pPoint2d &polygon0, int & polygon0_point_num, 
		pPoint2d &polygon1, int & polygon1_point_num);

	inline bool point_in_polygon(const float_t& px, const float_t& py, const point2d_t *polygon, std::size_t size)
	{
		bool result = false;
		if (size < 3) {
			ASSERT(0);
			return false;
		}
		std::size_t j = size - 1;
		for (std::size_t i = 0; i < size; ++i)
		{
			if (((polygon[i][1] <= py) && (py < polygon[j][1])) || // an upward crossing
				((polygon[j][1] <= py) && (py < polygon[i][1])))   // a downward crossing
			{
				/* compute the edge-ray intersect @ the x-coordinate */
				if (px - polygon[i][0]< ((polygon[j][0] - polygon[i][0]) * (py - polygon[i][1]) / (polygon[j][1] - polygon[i][1])))
				{
					result = !result;
				}
			}
			j = i;
		}
		return result;
	}
};

#endif //_graphy_polygon_h_